function getResolve(path) {
  return function (resolve) {
    require([`@/views${path}`], resolve)
  }
}

/**
 * 扁平化数据转树形结构 listToTree
 * @param {Array} list  // 数据
 * @param {String} id    // 根节点的键名
 * @param {String} pid   // 父节点的键名
 * @returns {Array} 树形结构数据
 */
export default ({
  list = [],
  id = 'id',
  pid = 'pid',
  children = 'children',
  map = {},
  metaMap = {}
}) => {
  const idMap = {}
  const tree = []

  // 布局组件映射
  const layoutMap = {
    Layout: () => import('@/layout/layoutPair'),
    SecondMain: () => import('@/layout/layoutPair/SecondMain')
  }

  // 创建一个映射，以便快速查找节点
  list.forEach((item) => {
    idMap[item[id]] = { ...item, meta: {} }
  })
  // 构建树形结构
  list.forEach((item) => {
    const currentItem = idMap[item[id]]
    const parentItem = idMap[item[pid]]

    // meta
    Object.keys(metaMap).forEach((metaMapKey) => {
      currentItem.meta[metaMapKey] = currentItem[metaMap[metaMapKey]]
    })

    // map
    Object.keys(map).forEach(async (mapKey) => {
      // 组件映射
      if (mapKey === 'component') {
        if (Object.keys(layoutMap).includes(currentItem[map[mapKey]])) {
          currentItem[mapKey] = layoutMap[currentItem[map[mapKey]]]
        } else {
          const componentPath = getResolve(currentItem[map[mapKey]])

          currentItem[mapKey] = componentPath
        }
      } else {
        // 普通值映射
        currentItem[mapKey] = currentItem[map[mapKey]]
      }
    })

    // 删除多余属性
    const whiteList = ['children', 'meta', 'component'] // 白名单

    Object.keys(currentItem).forEach((key) => {
      if (!whiteList.includes(key) && !Object.keys(map).includes(key)) {
        delete currentItem[key]
      }
    })

    if (parentItem) {
      if (typeof parentItem[children] === 'undefined') {
        parentItem[children] = []
      }
      parentItem[children].push(currentItem)
    } else {
      tree.push(currentItem)
    }
  })
  return tree
}
